﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


namespace XFFSM
{
    public class FSMTransition
    {
        #region 字段
        private FSMTransitionData data;
        private FSMController controller;
        private FSMStateNode toState;
        public List<FSMCondition> conditions;

        #endregion

        #region 属性
        public FSMTransitionData Data => data;
        #endregion


        public FSMTransition(FSMController controller, FSMTransitionData data) {
            this.data = data;
            this.controller = controller;

            this.conditions = new List<FSMCondition>();

            foreach (var item in this.data.conditions)
            {
                FSMCondition condition = new FSMCondition(item, controller);
                condition.onConditionMeet += this.CheckConditionIsMeet;
                this.conditions.Add(condition);
            }

            if ( controller.states.ContainsKey(data.toStateName) ) {
                toState = controller.states[data.toStateName];
            }

        }

        // 检测条件是不是都满足了
        public void CheckConditionIsMeet() {
            
            if (conditions.Count == 0) { return; }

            // 判断是不是所有的条件都满足了 
            foreach (var item in conditions)
            {
                if (item.state == ConditionState.NotMeet) return;
            }

            if (toState == null) { Debug.LogError("查询目标状态失败!");  return; }

            if ( !data.fromStateName.Equals(controller.currentState.data.name) ) {

                // AnyState
                if ( !data.fromStateName.Equals(FSMConst.anyState) ) { 
                    return;
                }


                // 判断当前的状态 跟 目标状态是不是一个 
                if ( controller.currentState.data.name.Equals(data.toStateName) ) {
                    return;
                }
            }


            // 切换状态 
            controller.SwitchState(toState,this);

        }


    }

}

